﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.Compilation;
using CSS.Common;

namespace CSS.Action
{
    public static class TemplateUtils
    {
        public static string LoadPage(string pagePath, NameValueCollection param)
        {
            var cachingDuration = AppSettings.GetInt32(Constants.CACHE_TEMPLATE_DURATION);

            var cacheName = "CSS_Cached_Template_" + Regex.Replace(pagePath, "\\|/", "_") + AppSettings.GetString(Constants.VERSION);
            if (HttpContext.Current.Cache[cacheName] != null && cachingDuration > 0)
            {
                return HttpContext.Current.Cache[cacheName].ToString();
            }
            else
                try
                {
                    // get the compiled type of referenced path
                    var type = BuildManager.GetCompiledType(pagePath);

                    // if type is null, could not determine page type
                    if (type == null)
                        throw new ApplicationException("Page " + pagePath + " not found");

                    // cast page object (could also cast an interface instance as well)
                    // in this example, ASP220Page is a custom base page
                    var pageView = (Core.PageBase)Activator.CreateInstance(type);
                    pageView.Params = param;

                    var writer = new StringWriter();
                    HttpContext.Current.Server.Execute(pagePath, writer, true);
                    var resultText = writer.ToString().Trim();
                    if (resultText != "" && cachingDuration > 0)
                        HttpContext.Current.Cache.Add(cacheName, resultText, null, DateTime.Now.AddHours(cachingDuration), TimeSpan.Zero, CacheItemPriority.High, null);

                    return resultText;
                }
                catch (Exception ex)
                {                   
                    return string.Empty;
                }
        }
    }
}
